package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.util.JwtUtils;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private FilterProperties filterProp;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    /**
     * 是否执行过滤器中的run方法
     * @return true：执行run方法；false：不执行run方法，意味着过滤器失效
     */
    @Override
    public boolean shouldFilter() {
        // 1.获取request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 2.判断路径是否需要放行
        boolean isAllowRequest = checkRequest(request);
        // 3.返回结果
        return !isAllowRequest;
    }

    private boolean checkRequest(HttpServletRequest request) {
        // 1.获取当前请求的路径
        String path = request.getRequestURI();
        // 2.获取当前请求的方式
        String method = request.getMethod();
        // 3.校验路径规则
        Map<String, String> allowPathMap = filterProp.getAllowPathMap();
        for (Map.Entry<String, String> entry : allowPathMap.entrySet()) {
            // 3.1.获取允许的路径
            String allowPath = entry.getKey();
            // 3.2.获取允许的方式
            String allowMethod = entry.getValue();
            // 3.3.路径判断
            if(!StringUtils.startsWith(path, allowPath)){
                // 路径不符合
                continue;
            }
            // 3.4.路径正确，判断method
            if (StringUtils.equalsIgnoreCase(allowMethod, "*") || StringUtils.equalsIgnoreCase(method, allowMethod)) {
                // 路径和method都正确，返回true
                return true;
            }
        }
        return false;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Object run() throws ZuulException {
        // 1.获取request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        try {
            // 2.获取cookie
            String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
            // 3.验证并解析cookie
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            // 4.验证黑名单
            Boolean isExists = redisTemplate.hasKey(payload.getId());
            if (BooleanUtils.isTrue(isExists)) {
                throw new RuntimeException("无效token");
            }
            UserInfo userInfo = payload.getUserInfo();
            log.info("用户{}正在访问{},验证通过！", userInfo.getUsername(), request.getRequestURI());

            ctx.set("user", userInfo);
        } catch (RuntimeException e) {
            // 5.都验不通过，拦截
            log.error("用户登录校验失败", e);
            // 拦截请求
            ctx.setSendZuulResponse(false);
            // 禁止访问
            ctx.setResponseStatusCode(403);
        }
        return null;
    }
}
